package com.softeem.ossmusic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softeem.ossmusic.comm.R;
import com.softeem.ossmusic.entity.Admin;
import com.softeem.ossmusic.mapper.AdminMapper;
import com.softeem.ossmusic.service.AdminService;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    public R login(String username, String password) {
        //根据用户名查询管理员信息 select * from admin where username=? and password=?
        QueryWrapper<Admin> query = Wrappers.query(Admin.class);
        query.eq("username",username);
        //根据查询条件查询管理员信息
        Admin admin = getOne(query);
        if(admin == null){
            return R.error().setMsg("账号不存在");
        }
        //判断密码
        if(!admin.getPassword().equals(password)){
            return R.error().setMsg("密码错误");
        }
        //账号是否禁用
        if(admin.getStatus() == 0){
            return R.error().setMsg("账号被禁用");
        }
        // 隐藏密码
        admin.setPassword(null);
        //登录成功
        return R.success().setData(admin);
    }

    @Override
    public R add(Admin admin) {
        QueryWrapper<Admin> query = Wrappers.query(Admin.class);
        query.eq("username",admin.getUsername());
        if(exists(query)){
            return R.error().setMsg("用户已存在");
        }
        // 设置新管理员状态为启用(1)
        admin.setStatus(1);
        // 设置创建时间
        admin.setCreateTime(new Timestamp(System.currentTimeMillis()));
        if(save(admin)){
            return R.success().setData(admin);
        }
        return R.error().setMsg("添加失败");
    }

    @Override
    public boolean existsById(Integer id) {
        return getById(id) != null;
    }
}
